package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.mapper.AdminMapper;
import com.example.blog.pojo.Admin;
import com.example.blog.pojo.LoginRequest;
import com.example.blog.pojo.Result;
import com.example.blog.service.AdminService;
import com.example.blog.util.TokenUtil.JwtUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Resource
    private AdminMapper adminMapper;

    /***
     * 管理员登录逻辑
     * @param loginRequest
     * @return 加密后的（SH256）密码，生成一个token
     */
    @Override
    public Result login(LoginRequest loginRequest, HttpServletResponse response) {
        if (StringUtils.isEmpty(loginRequest.getUsername()) || StringUtils.isEmpty(loginRequest.getPassword())) {
            return Result.ACCOUNT();
        }

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginRequest.getUsername());

        //查询是否有此用户
        Admin login = adminMapper.selectOne(queryWrapper);
        if (login == null) {
            return Result.failed();
        }
        //判断密码是否正确
        if (!login.getPassword().equals(loginRequest.getPassword())) {
            return Result.failed();
        }
        //将username加密（HS256）放入token中用来鉴权
        String Token = JwtUtils.createToken(loginRequest.getUsername() + ":" + loginRequest.getPassword());
        // 将 Token 存入 Cookie 中
        if (Token != null) {
            Cookie cookie = new Cookie("token", Token);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            return Result.success("登录成功！");
        }
        return Result.failed("登陆失败！");
    }

    @Override
    public Admin getByPassword(String password) {
        return lambdaQuery().eq(Admin::getPassword, password).one();
    }
}
